from datetime import timedelta

from dateutil.relativedelta import relativedelta

from odoo import models, fields, api
from odoo.exceptions import ValidationError, UserError
import datetime
import json
from odoo.tools.misc import xlwt
import base64
from io import BytesIO


class HrOvertimeWizard(models.TransientModel):
    _name = 'hr.overtime.wizard'
    date_start=fields.Date(string=u'开始时间')
    date_stop=fields.Date(string=u'结束时间')
    department_id=fields.Many2one('hr.department')
    employee_id=fields.Many2one('hr.employee')
    employee_type = fields.Selection([
        ('1', '月薪'),
        ('2', '日薪'),
        ('3', '小时工')
    ], string=u'职工类型')
    is_active=fields.Selection([
        ('1','在职'),
        ('2','离职')
    ],string=u'状态')


    # def action_confirm(self):
    #     import calendar
    #     day_now = self.date_time.strftime('%Y-%m-%d')  # 给定日期
    #     day_begin = day_now[0:7] + '-01'  # 月初肯定是1号 所以 直接替换 就可以
    #     monthRange = calendar.monthrange(int(day_now[0:3]), int(day_now[5:7]))  # 得到本月的天数
    #     day_end = day_now[0:7] + '-' + str(monthRange[1])
    #
    #     if self.department_id:
    #         employee_ids = self.env['hr.employee'].search([('department_id', '=', self.department_id.id)])
    #         record_id = self.env['hr.attendance.wizard'].create({
    #             'start_date': day_begin,
    #             'end_date': day_end,
    #             'department_id': self.department_id.id
    #         })
    #     else:
    #         employee_ids = self.env['hr.employee'].search([])
    #         record_id = self.env['hr.attendance.wizard'].create({
    #             'start_date': day_begin,
    #             'end_time': day_end,
    #         })
    #
    #     record_id.action_confirm()
    #
    #     month_time = day_now[0:7]
    #
    #     self._get_data_by_overtime(month_time,employee_ids)
    #


    def _get_data_by_overtime(self, date1, date2,employees):
        returnDict = {}
        days=[]
        while date1<=date2:
            days.append(date1)
            date1=date1+timedelta(days=1)


        purchase_sequence = 1
        for employee in employees:
            returnDict[employee.id] = {'data': {}, 'days': []}
            res={}
            for day in days:
                # hours=employee.get_overtime_data(day)
                hours=5
                res.update({day:hours})
            returnDict={'data':res}
        workbook = xlwt.Workbook(encoding='utf-8')
        mf = xlwt.XFStyle()  # 处理时间格式
        mf.num_format_str = 'yyyy-mm/-d'
        worksheet = workbook.add_sheet('测试 ', cell_overwrite_ok=True)

        # add header
        header = ['名称', '价格', '总票数', '余票', '门票时间', '淡旺季', '售出', '实际进入']
        for col in range(len(header)):
            worksheet.write(0, col, header[col])

        # add data
        # product_ids = self.env['ticket.management'].search([])  #用于取的此模型的所有数据
        for row in range(1, len(employees) + 1):
            product_id = employees[row - 1]
            worksheet.write(row, 0, product_id.name)
            # worksheet.write(row, 1, product_id.price)
            # worksheet.write(row, 2, product_id.total_number)
            # worksheet.write(row, 3, product_id.surplus)
            # worksheet.write(row, 4, product_id.ticket_date, mf)
            # worksheet.write(row, 5, product_id.price_id.name)
            # worksheet.write(row, 6, product_id.sold_out)
            # worksheet.write(row, 7, product_id.actual_entry)

        # save
        buffer = BytesIO()
        workbook.save(buffer)
        return base64.encodebytes(buffer.getvalue())

    def action_confirm(self):
        domain=[]
        if self.department_id:
            domain=[('department_id', '=', self.department_id.id)]
        if self.employee_id:
            domain=[('id', '=', self.employee_id.id)]
        if self.is_active:
            if self.is_active=='1':
                domain+=[('active','=',True)]
            elif self.is_active=='2':

                domain += [('active', '=', False),('resign_date','>=',self.date_start)]

        employee_ids=self.env['hr.employee'].with_context({'active_test':False}).search(domain)

        if self.employee_type:
            employee_ids=employee_ids.with_context({'active_test':False}).filtered(lambda x:x.employee_type==self.employee_type)

        context = dict(self._context or {})
        active_ids = context.get('active_ids', []) or []
        self.file = self._get_data_by_overtime(self.date_start,self.date_stop,employee_ids)


        action = {
            'type': 'ir.actions.act_url',
            'url': '/hr_overtime/export_hr_overtime/?date_start=' + str(self.date_start)+'&&date_stop='+str(self.date_stop)+'&&employee_ids='+str(employee_ids.ids),
            'nodestroy': True
        }
        return action




